package cn.iocoder.yudao.module.project.service.dispatchlist;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.project.config.projectDefine;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.*;
import cn.iocoder.yudao.module.project.controller.admin.dispatchlist.vo.*;
import cn.iocoder.yudao.module.project.dal.dataobject.dispatchlist.DispatchListDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.project.dal.mysql.dispatchlist.DispatchListMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.project.enums.ErrorCodeConstants.*;

/**
 * 派工单 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class DispatchListServiceImpl implements DispatchListService {

    @Resource
    private DispatchListMapper dispatchListMapper;

    @Override
    public Integer createDispatchList(DispatchListSaveReqVO createReqVO) {
        // 插入
        DispatchListDO dispatchList = BeanUtils.toBean(createReqVO, DispatchListDO.class);
        dispatchListMapper.insert(dispatchList);
        // 返回
        return dispatchList.getId();
    }

    @Override
    public void updateDispatchList(DispatchListSaveReqVO updateReqVO) {
        // 校验存在
        validateDispatchListExists(updateReqVO.getId());
        // 更新
        DispatchListDO updateObj = BeanUtils.toBean(updateReqVO, DispatchListDO.class);
        dispatchListMapper.updateById(updateObj);
    }

    @Override
    public void deleteDispatchList(Integer id) {
        // 校验存在
        validateDispatchListExists(id);
        // 删除
        dispatchListMapper.deleteById(id);
    }

    private void validateDispatchListExists(Integer id) {
        if (dispatchListMapper.selectById(id) == null) {
            throw exception(DISPATCH_LIST_NOT_EXISTS);
        }
    }

    @Override
    public DispatchListDO getDispatchList(Integer id) {
        return dispatchListMapper.selectById(id);
    }

    @Override
    public PageResult<DispatchListDO> getDispatchListPage(DispatchListPageReqVO pageReqVO) {
        return dispatchListMapper.selectPage(pageReqVO);
    }

    @Override
    public CommonResult<String> importExcel(InputStream inputStream) {
        ExcelReader excelReader = ExcelUtil.getReader(inputStream);
        List<List<Object>> tableList = excelReader.read();

        List<String> fieldList = new ArrayList<>();
        fieldList.add("shipmentDate");
        fieldList.add("customer");
        fieldList.add("ticketNumber");
        fieldList.add("internalNumber");
        fieldList.add("modelKp");
        fieldList.add("flex");
        fieldList.add("hammerPlateStructure");
        fieldList.add("hammerPlateModel");
        fieldList.add("direction");
        fieldList.add("quantity");
        fieldList.add("productLength");
        fieldList.add("tcf");
        fieldList.add("st1271");
        fieldList.add("remark");
        fieldList.add("bat");

        List<DispatchListDO> dispatchListDOList = new ArrayList<>();

        List<Integer> errorRowIndexList = new ArrayList<>();

        boolean errorFlag = false;
        int successCount = 0;
        int repeatCount = 0;

        if (CollectionUtil.isNotEmpty(tableList)) {
            int headIndex = 0;
            int size = tableList.size();
            for(int i = (headIndex + 1); i < size; i++){
                List<Object> rowsList = tableList.get(i);
                if (CollectionUtil.isNotEmpty(rowsList)) {
                    DispatchListDO dispatchListDO = new DispatchListDO();
                    dispatchListDO.setStatus(projectDefine.ORDER_STATUS.ORDER_STATUS_0);
                    for (int j = 0; j < rowsList.size(); j++) {
                        Object cellValue = rowsList.get(j);

                        if(j == 0 && (Objects.isNull(cellValue) || Objects.equals("", cellValue))){
                            break;
                        }
                        String fieldName = fieldList.get(j);
                        try {

                            if("ticketNumber".equalsIgnoreCase(fieldName)){
                                Long cnt = dispatchListMapper.selectCount(DispatchListDO::getTicketNumber, cellValue);
                                if(Objects.nonNull(cnt) && cnt > 0){
                                    repeatCount++;
                                    continue;
                                }
                            }

                            ReflectUtil.setFieldValue(dispatchListDO, fieldName, cellValue);
                        } catch (Exception e) {
                            errorFlag = true;
                            errorRowIndexList.add(i);
                        }
                    }
                    if(!errorFlag && !Objects.isNull(dispatchListDO.getShipmentDate()) && !Objects.equals("", dispatchListDO.getShipmentDate())){
                        dispatchListDOList.add(dispatchListDO);
                    }
                }
            }
        }

        if(!errorFlag){
            successCount = dispatchListDOList.size();
            dispatchListMapper.insertBatch(dispatchListDOList, 100);
            return CommonResult.success("导入成功, 成功记录数:" + successCount + "，重复记录数:" + repeatCount);
        }
        return CommonResult.error(DISPATCH_LIST_DATA_ERROR.getCode(), DISPATCH_LIST_DATA_ERROR.getMsg() + "，第" + String.join(",", errorRowIndexList.toString()) + "行数据错误");
    }
}
